package org.jwt.oauth.exception;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import javax.servlet.http.HttpServletResponse;

import org.jwt.oauth.response.ResponseData;
import org.jwt.oauth.tools.TimeTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ServiceExceptionHandler {

	private static final Logger log = LoggerFactory.getLogger(ServiceExceptionHandler.class);
	
	@ExceptionHandler(value = Exception.class)
	public ResponseEntity<ResponseData<Object>> defaultErrorHandler(HttpServletResponse response, Exception exception) {
		log.error("异常时间:{}",TimeTool.dateToString(null));
		log.error(exception.getMessage(),exception);
		Integer status = ServiceErrorStatus.REQUEST_ERROR.status();
		String message =ServiceErrorStatus.REQUEST_ERROR.message();
		String describe = exception.getMessage();
		if (exception instanceof ServiceRunTimeException) {
			ServiceRunTimeException httpException = (ServiceRunTimeException) exception;
			Integer serviceStatus = httpException.getStatus();
			if(serviceStatus!=null) {
				status = serviceStatus;
			}
			String serviceMessage = httpException.getMessage();
			if(serviceMessage!=null && serviceMessage.trim().length() > 0) {
				message=serviceMessage;
			}
			String serviceDescribe = httpException.getDescribe();
			if(serviceDescribe!=null && serviceDescribe.trim().length() > 0) {
				describe=serviceDescribe;
			}
			ResponseData<Object> errorMessage = ResponseData.ERROR(status, message, describe);
			return ResponseEntity.status(httpException.getHttpStatus()).body(errorMessage);
		}
		ResponseData<Object> errorMessage = ResponseData.ERROR(status, message, describe);
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage);
	}
	
	public static String getExceptionInfo(Exception exception) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(out);
        exception.printStackTrace(printStream);
        String exceptionInfo = new String(out.toByteArray());
        try {
            printStream.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return exceptionInfo;
    }
}
